package com.itheima.exerciseTest.method40_49.method42;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

public class Demo {
    public static void main(String[] args) throws DocumentException {
        // 获取解析器对象
        SAXReader saxReader = new SAXReader();

        // 解析指定xml配置文件，获得文件的Document对象
        Document document = saxReader.read(new File("myCode\\xml\\student2.xml"));

        // 通过Document对象获得根标签
        Element rootElement = document.getRootElement();

        // 通过根标签来获取所有的student标签，并存入集合中
        List<Element> studentElements = rootElement.elements("student");

        ArrayList<Student> al = new ArrayList<>();
        HashSet<Student> hs = new HashSet<>();

        // 遍历
        for (Element element : studentElements) {
            // 获得id属性
            Attribute attribute = element.attribute("id");
            // 获得id属性值
            String id = attribute.getValue();

            // name
            Element nameElement = element.element("name");
            String name = nameElement.getText();

            // age
            Element ageElement = element.element("age");
            String age = ageElement.getText();

            Student student = new Student();
            student.setId(id);
            student.setName(name);
            student.setAge(Integer.parseInt(age));

            al.add(student);
            hs.add(student);
        }

        System.out.println("================ArrayList================");
        for (Student student : al) {
            System.out.println(student);
        }

        System.out.println("\n================HashSet================");
        for (Student student : hs) {
            System.out.println(student);
        }

    }
}
